package com.ruoyi.auth.form;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import java.util.HashMap;
import java.util.Map;

/**
 * 手机短信发送工具类
 * @author ruoyi
 */
public class MobileMessageUtil {
    private static final Logger log = LoggerFactory.getLogger(MobileMessageUtil.class);

    /**
     * 发送手机验证码
     * @param mobile 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public static Boolean sendMobileMessage(String mobile, String code) {
        try {
            log.info("开始发送验证码: 手机号={}, 验证码={}", mobile, code);
            
            // 构建请求参数
            String host = "https://gyytz.market.alicloudapi.com";
            String path = "/sms/smsSend";
            String method = "POST";
            
            // 配置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + "你的AppCode"); // 替换为实际的AppCode
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            
            // 配置请求参数
            Map<String, String> querys = new HashMap<>();
            Map<String, String> bodys = new HashMap<>();
            bodys.put("mobile", mobile);
            bodys.put("param", "code:" + code);
            bodys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2"); // 替换为实际的短信签名ID
            bodys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad"); // 替换为实际的短信模板ID
            
            // 发送请求
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            
            // 处理响应
            int statusCode = response.getStatusLine().getStatusCode();
            String responseContent = EntityUtils.toString(response.getEntity());
            
            log.info("发送验证码响应: 状态码={}, 响应内容={}", statusCode, responseContent);
            
            // 检查响应状态
            if (statusCode >= 200 && statusCode < 300) {
                log.info("验证码发送成功: 手机号={}", mobile);
                return true;
            } else {
                log.error("验证码发送失败: 手机号={}, 状态码={}, 错误信息={}", 
                    mobile, statusCode, responseContent);
                return false;
            }
        } catch (Exception e) {
            log.error("发送验证码异常: 手机号={}", mobile, e);
            return false;
        }
    }
}
